import Bug from "./Bug.js";
import Snake, { snakes } from "./Snake.js";
import config from "./config.js";
export default class Play {
  //运动方向
  direction;
  inertvalId;
  constructor(app) {
    this.$app = app;
    this.bindDocumentEvent();
  }
  //启动动画
  play() {
    this.inertvalId = setInterval(this.run.bind(this), config.rate);
  }
  reset() {
    clearInterval(this.inertvalId);
    this.play();
  }
  //移动处理
  run() {
    snakes.reduce((position, snake) => {
      //设置蛇新的位置
      snake.left = position.left;
      snake.top = position.top;
      return snake.oldPosition;
    }, this.position());

    //检测小虫碰撞
    this.crashBug();

    //画布边界碰撞
    this.crashCanvas();
  }

  crashCanvas() {
    const snake = Snake.first;

    if (
      snake.left < 0 ||
      snake.top < 0 ||
      snake.left > config.canvas.width - config.width ||
      snake.top > config.canvas.height - config.height
    ) {
      this.gameOver();
    }
  }

  gameOver() {
    clearInterval(this.inertvalId);
    this.$app.renderTotal("游戏结束!");
  }
  //与小虫碰撞检测
  crashBug() {
    if (Snake.first.left == Bug.left && Snake.first.top == Bug.top) {
      this.$app.snake({
        left: Snake.last.oldPosition.left,
        top: Snake.last.oldPosition.top,
      });

      //移除小虫子
      Bug.remove();
      this.$app.bug();
      //调整运行时间
      config.rate = Math.max(50, config.rate - 20);
      this.reset();
      this.$app.renderTotal();
    }
  }

  //绑定键盘事件
  bindDocumentEvent() {
    document.addEventListener("keydown", (event) => {
      this.direction = event.key.substr(5).toLowerCase();
      //启动动画
      if (!this.inertvalId) this.play();
    });
  }

  //获取到蛇头移动新位置
  position() {
    const position = { left: Snake.first.left, top: Snake.first.top };
    switch (this.direction) {
      case "up":
        position.top = position.top - config.height;
        break;
      case "down":
        position.top = position.top + config.height;
        break;
      case "left":
        position.left = position.left - config.width;
        break;
      case "right":
        position.left = position.left + config.width;
        break;
    }
    return position;
  }
}
